<template>
    <div>
        <div class="cabinet-components-container " v-if="cabinetList.length">
            <carousel :per-page="3" @navigation-click="changePage" :mouse-drag="false" :scrollPerPage="true"
                navigationEnabled :paginationEnabled="false" :touchDrag="false">
                <slide v-for="(item, i) in cabinetList" :key="i">
                    <div @click="slideClick(item)" class="slide-wrap" v-show="item.isHas">
                        <div>
                            <img class="alarm" :src="alterLevelImg(item.alterLevel)" alt="">
                        </div>
                        <div :class="['cabinet-item', item.resourceNum == cabinetInfo.resourceNum ? 'active' : '']">
                            <!-- 机柜背景图 -->
                            <img :src="activeBg(item)" class="cabinet-bg">
                            <div class="resourceNum text-ov">{{ item.resourceName }}</div>
                            <!-- 机柜列表 -->
                            <div class="cabinet-list">
                                <div v-for="n in nums" class="flex"
                                    @mouseenter.self="enterCabinet(getUdetail(item.udetailList, n), $event)">
                                    <div class="index"> {{ n }}</div>
                                    <div :class="[
                                        'item flex-ac',

                                        //U位状态
                                        getUStatus.get(getUdetail(item.udetailList, n).ustatus),

                                        //高亮状态
                                        getUdetail(item.udetailList, n).isBright ? 'bright' : '',

                                        // U位上有资源
                                        getUdetail(item.udetailList, n) ? 'uheight' : ''
                                    ]">

                                        <!-- 有资源 -->
                                        <template v-if="getUdetail(item.udetailList, n).startU == n">
                                            <span :class="['status', uStatus(getUdetail(item.udetailList, n).pilotStatus)]">
                                            </span>
                                            <div class="flex-ac">
                                                <img width="12" height="12"
                                                    :src="getImgSrc(3, getUdetail(item.udetailList, n).resourceTypeId)">
                                                <div class="text text-ov">
                                                    {{ getUdetail(item.udetailList, n).resourceName }}
                                                </div>
                                            </div>
                                        </template>
                                        <!-- 能拖动的位置 -->
                                        <drop
                                            :class="['drop', recommU({ ...item, assetU: item.uHeight }, n, item.resourceNum) ? 'recomm' : '']"
                                            v-else-if="!getUdetail(item.udetailList, n)"
                                            @dragenter="handleDrop({ startU: n, resourceNum: item.resourceNum, resourceName: item.resourceName }, ...arguments)"
                                            @drop="handleDrop({ startU: n, resourceNum: item.resourceNum, resourceName: item.resourceName }, ...arguments)">
                                            <drag :class="{ 'over': formatuHeight(n, item.resourceNum), 'flex-ac': true }"
                                                :transfer-data="{ data: formatuHeight(n, item.resourceNum) }">
                                                <template
                                                    v-if="formatuHeight(n, item.resourceNum) && formatuHeight(n, item.resourceNum).startU == n">
                                                    <img width="12" height="12" style="margin-left:5px"
                                                        :src="getImgSrc(3, formatuHeight(n, item.resourceNum).resourceTypeId)">
                                                    <div class="text text-ov"> {{ formatuHeight(n,
                                                        item.resourceNum).hostName }} </div>
                                                </template>
                                            </drag>
                                        </drop>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </slide>
            </carousel>

            <div class="cabinet-modal" v-show="showModal && show" @mouseenter="modalEnter" @mouseleave="leaveCabinet">
                <el-row type="flex" class="modal-title" justify="space-between">
                    <div>资产信息</div>
                    <div v-if="dynamicData[0] && dynamicData[0].dateTime">{{ formatDate(dynamicData[0].dateTime) }}</div>
                </el-row>
                <div class="model-content">
                    <div>
                        <div v-for="array in staticData" class="flex staticData">
                            <!-- <div class="mb20"><span class="line"></span> 基础信息</div> -->
                            <template v-for="list in array">
                                <div v-for="ar in list" class="flex">
                                    <div class="static-title">{{ ar.columnComments }}:</div>
                                    <div class="text-ov">{{ ar.columnName }}</div>
                                </div>
                            </template>
                        </div>
                    </div>
                    <div>
                        <!-- <div class="mb20"><span class="line"></span> 运行数据</div> -->
                        <div class="staticData flex">
                            <div v-for="item in dynamicData" class="flex">
                                <div class="static-title">
                                    {{ item.columnComments }}:
                                </div>
                                <div>{{ item.columnValue }}</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>  
<script>
import { getMonitorStaticDetail, getMonitorData } from "@/api/computerRoomApi.js";
import utils from "@/utils/date.js"
// import { Carousel, Slide } from 'vue-carousel';
import { Carousel, Slide } from '../../utils/vue-carousel.min.js'
import imgSrc from "../../utils/imgSrc";
export default {
    name: "CabinetComponts",
    components: {
        Carousel,
        Slide,
    },
    props: {
        // 显示u位信息弹窗
        showModal: {
            type: Boolean,
            default: false
        },
        // 显示的机柜ids列表
        cabinetIdList: {
            type: Array,
            defaule: []
        },
        // 显示的机柜列表
        cabinetList: {
            type: Array,
            defaule: []
        },
        // U位能否拖动
        isDrag: {
            type: Boolean,
            default: false
        }
    },
    // 加载机柜列表，选中的机柜
    emit: ["loadData", "selectCabinet"],
    data() {
        return {
            nums: [
                '42', '41', '40', '39', '38', '37', '36', '35', '34', '33', '32', '31', '30',
                '29', '28', '27', '26', '25', '24', '23', '22', '21', '20',
                '19', '18', '17', '16', '15', '14', '13', '12', '11', '10',
                '09', '08', '07', '06', '05', '04', '03', '02', '01'
            ],
            form: {
                selectValue: "",//下拉选中
                hostName: "",//主机名
                resourceName: "",//资源名
            },
            rules: {
                name: [
                    { required: true, message: "请输入机房名称", trigger: "blur" },
                    // { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
                ],
            },//
            timer: 0,
            cabinetInfo: {},//当前选中的机柜信息
            show: false,//显示资源悬浮弹窗
            dynamicData: [],//动态数据
            staticData: [],//静态数据 
            showModalId: "",
            enterTimer: 0,
            over: false,
            dragTimer: 0,
            getUStatus: new Map([
                [1, 'bg1'],
                [2, 'bg2'],
                [3, 'bg3']
            ]),// U位状态
            dropAssets: [],//拖放后的数据
        }
    },

    mounted() {
        if (!this.isDrag) {
            let unwatch = this.$watch(
                function () {
                    if (this.cabinetList.length) {
                        this.cabinetInfo = this.cabinetList[1];
                        // console.log(this.cabinetInfo);
                        this.$emit("selectCabinet", this.cabinetInfo);
                        unwatch();
                    }
                }
            );
        }
    },
    methods: {
        formatDate(date) {
            return utils.formatter(date, "yyyy-MM-dd hh:mm:ss")
        },

        getImgSrc(type, id) {
            return imgSrc(type, id)
        },

        uStatus(number) {
            let status = ""
            switch (number) {
                case 1:
                    //指示灯的状态  
                    //1-绿色：常亮表示正常无告警
                    status = "status1"
                    break;
                case 2:
                    //2-绿色闪烁：表示有一般告警
                    status = "status1"
                    break;
                case 3:
                    //3-红色闪烁：表示有紧急告警
                    status = "status2"
                    break;
                case 4:
                    //4-黄色闪烁：表示有重要告警
                    status = "status3"
                    break;    
                default:
                    status = "status4"
                    break;
            }
            return status
        },

        // 点击机柜
        slideClick(obj) {
            if (this.isDrag) {
                return
            }
            this.cabinetInfo = obj;
            this.$emit("selectCabinet", this.cabinetInfo)
        },

        /**
         * 拖放的数据
         * @param {*} info {startU,resourceNum,resourceName}起始U和机柜编号
         * @param {*} data 
         */
        handleDrop(info, data) {
            if (this.dragTimer) {
                clearTimeout(this.dragTimer)
            }

            let findIndex = this.dropAssets.findIndex(({ id }) => data.data.id == id);

            let usedU = new Map();
            this.cabinetList.map((item) => {
                if (item.udetailList) {
                    item.udetailList.map((uItem) => {
                        usedU.set(item.resourceNum, [...usedU.get(item.resourceNum) ?? [], uItem.startU, uItem.startU - 1, uItem.startU + uItem.heightU, 42, 1])
                    })
                }
            })
            // 判断不能存放的位置
            if (usedU.get(info.resourceNum)) {
                let num = (Number(data.data.assetU) + Number(info.startU));
                usedU.get(info.resourceNum).push(num)

                if (usedU.get(info.resourceNum).includes(Number(info.startU)) || usedU.get(info.resourceNum).includes(num - 1)) {
                    this.dragTimer = setTimeout(() => {
                        this.message("当前U位不能分配", 3);
                    }, 500);
                    this.dropAssets.splice(findIndex, 1)
                    return;
                }

            }

            // 已经在机柜
            if (findIndex > -1) {
                this.dropAssets.splice(findIndex, 1, { ...data.data, ...info })
            } else {
                // 没有在机柜的
                this.dropAssets.push({ ...data.data, ...info })
            }
        },
        // 
        changePage(d) {
            let resourceId = "";
            let flag = d === "backward";
            // 向前
            if (flag) {
                resourceId = this.cabinetList.find(({ resourceNum }) => resourceNum).resourceNum;
            } else {
                // 向后 forward
                resourceId = this.cabinetList.reverse().find(({ resourceNum }) => resourceNum).resourceNum;
            }
            let index = this.cabinetIdList.findIndex((id) => id == resourceId);
            if (flag) {
                index - 1
            } else {
                index + 1
            }
            let id = this.cabinetIdList[index];

            if (id == this.cabinetIdList[0]) {
                this.message("当前在第一页")
                return;
            }
            if (resourceId == this.cabinetIdList[this.cabinetIdList.length - 1]) {
                this.message("当前在最后一页")
                return;
            }
            this.$emit("loadData", { id, type: flag ? 1 : 2 })
        },

        /**
         * 计算区间
         * @param {*} array udetailList
         * @param {*} value 起始U
         */
        getUdetail(array, value) {
            if (!array) return false
            let uIndex = array.findIndex(({ startU, heightU }) => value < (startU + heightU) && value >= startU);
            if (uIndex > -1) {
                return array[uIndex]
            }
            return false
        },
        /**
         * 计算符合Uheight
         * @param {*} value 当前机柜位置
         * @param {*} resourceNum 当前机柜编号
         */
        formatuHeight(value, resourceNum) {
            if (!this.dropAssets.length) return false
            let uIndex = this.dropAssets.findIndex((item) => value < (Number(item.startU) + Number(item.assetU)) && value >= item.startU && item.resourceNum == resourceNum);
            if (uIndex > -1) {
                return this.dropAssets[uIndex]
            }
            return false
        },

        recommU(data, value, resourceNum) {
            if (!data.startU) return false
            return value < (Number(data.startU) + Number(data.uheight)) && value >= data.startU && data.resourceNum == resourceNum
        },

        // 机柜背景图
        activeBg(item) {
            if (item.resourceNum == this.cabinetInfo.resourceNum) {
                return require("../../assets/computerRoom/active-cabinet-bg.png")
            }
            return require("../../assets/computerRoom/cabinet-bg.png")
        },

        // 机柜告警
        alterLevelImg(status) {
            if (status == 1) {
                return require("../../assets/computerRoom/alarm1.png")
            } else if (status == 1) {
                return require("../../assets/computerRoom/alarm2.png")
            }
            return require("../../assets/computerRoom/alarm2.png")
        },

        modalEnter() {
            clearTimeout(this.timer)
        },

        // 鼠标进入资源
        enterCabinet(item, event) {

            if (this.enterTimer) {
                clearTimeout(this.enterTimer)
            }
            this.enterTimer = setTimeout(async () => {
                this.staticData = [];
                this.dynamicData = [];
                // console.log(item);
                if (!item) {
                    this.show = false;
                    return
                }

                const data = await this.getModalData(item.resourceId, item.resourceTypeId);
                if (data[0].code == "200") {
                    this.staticData = data[0].info
                }
                if (data[1].code == "200") {
                    this.dynamicData = data[1].info
                }
                // console.log(this.staticData, this.dynamicData);
                clearTimeout(this.timer);
                let modalEl = document.querySelector(".cabinet-modal");
                const { clientX, clientY } = event;
                let letPx = clientX - 654;
                let topPx = clientY - 50
                // console.log(letPx, modalEl.clientWidth);
                if (topPx < 50) {
                    topPx = 50
                }
                if (topPx > 550) {
                    topPx = 550
                }
                modalEl.style.left = letPx + "px";
                modalEl.style.top = topPx + "px"
                // console.log(item, event);
                this.show = true;
                this.showModalId = item.resourceId
            }, 200);


        },

        getModalData(resourceId, resourceTypeId) {
            return Promise.all([
                getMonitorStaticDetail({ resourceId, resourceTypeId }),
                getMonitorData({ resourceId, resourceTypeId })
            ])
        },

        // 鼠标离开
        leaveCabinet() {
            console.log("鼠标离开");
            this.timer = setTimeout(() => {
                this.show = false;
                this.showModalId = ""
            }, 1000);
        },
    },
}
</script>
<style  lang="scss">
.cabinet-components-container {
    width: 900px;
    margin: 0 auto;
    height: 94%;
    overflow: auto;

    .VueCarousel {
        width: 800px;
        margin: 0 auto;

        .VueCarousel-navigation {
            height: 40px;

            .VueCarousel-navigation-button {
                width: 40px;
                height: 40px;
                border-radius: 50%;
                background-color: #000;
                opacity: .3;

                // position: relative;

                &.VueCarousel-navigation-prev {

                    &:before {
                        content: "";
                        position: absolute;
                        top: 10px;
                        right: 13px;
                        width: 15px;
                        height: 20px;
                        background: url('../../assets/computerRoom/arrow.png') no-repeat;
                        background-size: 100% 100%;
                    }
                }

                &.VueCarousel-navigation-next {
                    &:before {
                        content: "";
                        position: absolute;
                        top: 10px;
                        right: 10px;
                        width: 15px;
                        height: 20px;
                        background: url('../../assets/computerRoom/arrow.png') no-repeat;
                        background-size: 100% 100%;
                        transform: rotateY(180deg);

                    }
                }
            }


        }
    }

    .VueCarousel-slide {

        .slide-wrap {
            width: 250px;
            margin: 0 auto;
            display: flex;
            flex-direction: column;
            align-items: center;
        }
    }

    .alarm {
        width: 21px;
        height: 21px;
        display: block;
    }

    .cabinet-item {
        width: 100%;
        height: 741px;
        color: #fff;
        font-size: 12px;
        position: relative;

        .resourceNum {
            position: absolute;
            width: 100%;
            font-size: 12px;
            line-height: 32px;
            text-align: center;
        }

        .cabinet-bg {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            z-index: -1;
        }

        &.active {
            .cabinet-list {
                width: 85%;
            }

            .index {
                width: 20px;
            }
        }

        .cabinet-list {
            width: 86%;
            height: 691px;
            position: absolute;
            top: 29px;
            left: 17px;

            .flex:nth-child(odd) .item {
                background: #FFF;
            }

            .flex:nth-child(even) .item {
                background: #F0F0F0;
            }

            .item {
                flex: 1;
                color: #333;
                overflow: hidden;

                .text {
                    width: 150px;
                    margin-left: 5px;
                }

                .drop {
                    width: 100%;
                    height: 100%;

                    &.recomm {
                        background: rgba(33, 183, 149, 0.2);
                    }

                    .over {
                        border-color: #21B795;
                        background: #21B795;
                        color: #fff;
                        width: 100%;
                        height: 100%;
                        cursor: pointer;
                    }
                }

                .status {
                    width: 10px;
                    height: 10px;
                    border-radius: 50%;
                    margin: 0 5px;
                    flex-shrink: 0;
                    display: inline-block;
                }

                .status1 {
                    background: #21B795;
                }

                .status2 {
                    background: #EA305C;
                }

                .status3 {
                    background: #FFCC00;
                }
            }

            .index {
                width: 17px;
                height: 16.5px;
            }

            .flex {

                .item.bg1 {
                    background-color: rgba(234, 48, 92, 0.25);
                }

                .item.bg2 {
                    background-color: rgba(184, 51, 240, 0.25);
                }

                .item.bg3 {
                    background-color: rgba(0, 150, 255, 0.25);
                }

                .item.bg4 {
                    background-color: #B4B4B4;
                }

                .item.bg5 {
                    background-color: #21B795;
                    border: 1px solid #21B795;
                }

                .item.uheight {
                    background-color: #B4B4B4;
                }

                .item.uheight.bright {
                    // border: 1px solid #21B795;
                    background: rgba(33, 183, 149, .6);
                }
            }
        }
    }
}

.cabinet-modal {
    width: 404px;
    height: 307px;
    background: rgba(0, 0, 0, 0.75);
    box-shadow: 1px 2px 7px 0px rgba(0, 0, 0, 0.6);
    padding: 20px 15px;
    box-sizing: content-box;
    position: absolute;
    top: -1000px;
    left: -1000px;
    transition: .2s all;
    border-radius: 6px;
    color: #fff;
    font-size: 14px;

    .modal-title {
        padding-bottom: 10px;
        position: relative;
    }

    .modal-title ::before {
        content: "";
        position: absolute;
        width: 433px;
        height: 1px;
        background-color: rgba(240, 240, 240, .6);
        bottom: 0px;
        left: -14px;
    }

    .model-content {
        height: 90%;
        overflow: auto;

        .staticData {
            flex-wrap: wrap;

            >div {
                width: 50%;
                margin-bottom: 10px;

            }

            .flex {
                .static-title {
                    width: 45%;
                }
            }
        }

        .dynamicData {
            flex-wrap: wrap;

            div {
                margin-bottom: 10px;
                width: 50%;
            }
        }
    }

    .mb20 {
        margin: 5px 0 10px 0;
    }

    // .flex {
    //     margin: 5px 0;

    //     >div:nth-child(1) {
    //         width: 45%;
    //     }
    // }
}

.flex-ac {
    display: flex;
    align-items: center;
}

.mt15 {
    margin-top: 15px;
}

.flex {
    display: flex;
}

.flex-jsb {
    display: flex;
    justify-content: space-between;
}

.mt25 {
    margin-top: 25px;
}
</style>
